import { Fragment, useEffect, useRef, useState } from "react";
import { Avatar, Spin, Tag, Button, message, Checkbox, Tooltip } from "antd";
import { AudioOutlined, CheckSquareOutlined, BorderOutlined, SoundOutlined, LoadingOutlined } from "@ant-design/icons";
import AvatarImage from "@/assets/images/avatar.png";
import { useAppSelector } from "@/store";
import MarkdownRenderer from "@/pages/components/MarkdownRenderer";
import { post } from "@/api/config";

interface SelectedMessage {
  index: number;
  content: string;
  type: 'user' | 'assistant';
  reasoningContent?: string;
}

const Content = () => {
  const chatListRef = useRef<HTMLDivElement>(null);
  const { messages, currentAnswer, currentReasoning, isLoading, reasoningTime, documentSearch } = useAppSelector(state => state.chat);
  const [messageApi, contextHolder] = message.useMessage();
  const [selectedMessages, setSelectedMessages] = useState<SelectedMessage[]>([]);
  const [isSelectionMode, setIsSelectionMode] = useState(false);
  const [ttsStates, setTtsStates] = useState<Record<string, { status: 'idle' | 'generating' | 'completed' | 'error'; audioUrl?: string }>>({});
  const audioRefs = useRef<Record<string, HTMLAudioElement | null>>({});
  const currentlyPlayingKeyRef = useRef<string | null>(null);
  const hoverToPlayRef = useRef<Record<string, boolean>>({});
  const [autoTTSEnabled, setAutoTTSEnabled] = useState(true); // 自动TTS开关

  useEffect(() => {
    if (chatListRef.current) {
      chatListRef.current.scrollTop = chatListRef.current.scrollHeight;
    }
  }, [messages, currentAnswer, currentReasoning]);

  // 选择消息
  const handleMessageSelect = (index: number, content: string, type: 'user' | 'assistant', reasoningContent?: string) => {
    const existingIndex = selectedMessages.findIndex(msg => msg.index === index);
    
    if (existingIndex >= 0) {
      // 取消选择
      setSelectedMessages(prev => prev.filter((_, i) => i !== existingIndex));
    } else {
      // 添加选择
      setSelectedMessages(prev => [...prev, { index, content, type, reasoningContent }]);
    }
  };

  // 全选所有消息
  const handleSelectAll = () => {
    const selectableMessages = messages
      .filter((msg, index) => index > 0) // 排除第一条欢迎消息
      .map((msg, originalIndex) => ({
        index: originalIndex,
        content: msg.content,
        type: msg.role as 'user' | 'assistant',
        reasoningContent: msg.reasoningContent || undefined
      }));
    
    setSelectedMessages(selectableMessages);
  };

  // 取消全选
  const handleDeselectAll = () => {
    setSelectedMessages([]);
  };

  // 转换选中的消息
  const handleConvertSelected = async () => {
    if (selectedMessages.length === 0) {
      messageApi.warning('请先选择要转换的消息');
      return;
    }

    try {
      const loadingKey = 'selected-tts-loading';
      messageApi.loading({ 
        content: '正在生成语音...', 
        key: loadingKey, 
        duration: 0 
      });
      
      // 构建选中消息的文本
      const selectedText = selectedMessages
        .sort((a, b) => a.index - b.index) // 按原始顺序排序
        .map(msg => {
          const role = msg.type === 'user' ? '用户' : '鼎盛';
          let content = msg.content;
          
          if (msg.reasoningContent) {
            content = `思考过程：${msg.reasoningContent}\n回答：${content}`;
          }
          
          return `${role}：${content}`;
        })
        .join('\n\n');
      
      const response = await post<{success: boolean; audioUrl?: string; error?: string}>('/user/tts', {
        text: selectedText
      }, {
        timeout: 600000
      });
      
      if (response.data?.success) {
        // 创建下载链接并自动下载
        const link = document.createElement('a');
        link.href = response.data.audioUrl!;
        link.download = `selected_messages_${Date.now()}.wav`;
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
        
        messageApi.success({ 
          content: `${selectedMessages.length}条消息语音生成成功，正在下载...`, 
          key: loadingKey 
        });
        
        // 显示下载完成提示
        setTimeout(() => {
          messageApi.success('音频文件已下载完成！');
        }, 1000);
      } else {
        messageApi.error({ 
          content: '语音生成失败，请稍后重试', 
          key: loadingKey 
        });
      }
    } catch (error) {
      console.error('选中消息TTS错误:', error);
      messageApi.error({ 
        content: '语音生成失败，请稍后重试', 
        key: 'selected-tts-loading' 
      });
    }
  };

  // 单条消息TTS处理
  // 清理Markdown格式，移除语法符号
  const cleanMarkdownForTTS = (text: string): string => {
    return text
      // 移除Markdown标题符号（包括#和##等）
      .replace(/^#{1,6}\s+/gm, '')
      // 移除粗体符号（**text** 或 __text__）
      .replace(/\*\*(.*?)\*\*/g, '$1')
      .replace(/__(.*?)__/g, '$1')
      // 移除斜体符号（*text* 或 _text_）
      .replace(/\*([^*]+)\*/g, '$1')
      .replace(/_([^_]+)_/g, '$1')
      // 移除代码块符号
      .replace(/```[\s\S]*?```/g, '')
      // 移除行内代码符号
      .replace(/`([^`]+)`/g, '$1')
      // 移除链接格式，只保留文本
      .replace(/\[([^\]]+)\]\([^)]+\)/g, '$1')
      // 移除图片格式
      .replace(/!\[([^\]]*)\]\([^)]+\)/g, '$1')
      // 移除引用符号
      .replace(/^>\s+/gm, '')
      // 移除列表符号
      .replace(/^[\s]*[-*+]\s+/gm, '')
      // 移除数字列表
      .replace(/^[\s]*\d+\.\s+/gm, '')
      // 移除水平分割线
      .replace(/^[\s]*[-*_]{3,}[\s]*$/gm, '')
      // 移除表格符号
      .replace(/\|/g, ' ')
      // 移除HTML标签
      .replace(/<[^>]+>/g, '')
      // 移除特殊Markdown符号
      .replace(/\*\*/g, '')  // 移除剩余的**
      .replace(/##/g, '')    // 移除剩余的##
      .replace(/###/g, '')   // 移除剩余的###
      .replace(/####/g, '')  // 移除剩余的####
      .replace(/#####/g, '') // 移除剩余的#####
      .replace(/######/g, '') // 移除剩余的######
      // 清理多余的空行
      .replace(/\n\s*\n/g, '\n')
      // 清理首尾空白
      .trim();
  };

  const handleSingleMessageTTS = async (index: string, content: string, role: 'user' | 'assistant') => {
    // 如果已经生成过TTS，重新下载
    if (ttsStates[index]?.status === 'completed' && ttsStates[index]?.audioUrl) {
      try {
        // 使用window.open方式，可能更少弹窗
        const downloadUrl = ttsStates[index].audioUrl!;
        const filename = `${role}_message_${index}_${Date.now()}.mp3`;
        
        // 尝试使用window.open
        const newWindow = window.open(downloadUrl, '_blank');
        if (newWindow) {
          setTimeout(() => {
            newWindow.close();
          }, 1000);
        }
        
        // 静默重新下载
      } catch (error) {
        console.error('重新下载失败:', error);
      }
      return;
    }

    // 如果正在生成中，不重复请求
    if (ttsStates[index]?.status === 'generating') {
      return;
    }

    try {
      // 设置生成中状态
      setTtsStates(prev => ({
        ...prev,
        [index]: { status: 'generating' }
      }));

      // 清理Markdown格式，然后调用TTS API
      const cleanedContent = cleanMarkdownForTTS(content);
      
      // 调用TTS API，传递角色信息以区分声音
      const response = await post<{success: boolean; audioUrl?: string; error?: string}>('/user/tts', {
        conversation: [{
          role: role,
          content: cleanedContent
        }]
      }, {
        timeout: 600000
      });

      if (response.data?.success && response.data.audioUrl) {
        // 设置完成状态
        setTtsStates(prev => ({
          ...prev,
          [index]: { 
            status: 'completed', 
            audioUrl: response.data.audioUrl 
          }
        }));

        // 不自动下载，静默处理
      } else {
        throw new Error(response.data?.error || '语音生成失败');
      }
    } catch (error) {
      console.error('单条消息TTS错误:', error);
      
      // 设置错误状态
      setTtsStates(prev => ({
        ...prev,
        [index]: { status: 'error' }
      }));

      messageApi.error('语音生成失败，请稍后重试');
    }
  };

  // 获取TTS状态图标
  const getTTSIcon = (index: string) => {
    const state = ttsStates[index];
    if (!state || state.status === 'idle') {
      return <SoundOutlined className="text-gray-400 hover:text-blue-500 transition-colors" />;
    }
    
    switch (state.status) {
      case 'generating':
        return <LoadingOutlined className="text-blue-500 animate-spin" />;
      case 'completed':
        return <SoundOutlined className="text-green-500" />;
      case 'error':
        return <SoundOutlined className="text-red-500" />;
      default:
        return <SoundOutlined className="text-gray-400" />;
    }
  };

  // 获取TTS提示文本
  const getTTSTooltip = (index: string) => {
    const state = ttsStates[index];
    if (!state || state.status === 'idle') {
      return '悬停生成语音';
    }
    
    switch (state.status) {
      case 'generating':
        return '正在生成语音...';
      case 'completed':
        return '点击下载语音';
      case 'error':
        return '生成失败，点击重试';
      default:
        return '悬停生成语音';
    }
  };

  // 检查消息是否被选中
  const isMessageSelected = (index: number) => {
    return selectedMessages.some(msg => msg.index === index);
  };

  // 渲染文档检索状态
  const renderDocumentSearchStatus = () => {
    if (!documentSearch.hasRelevantDocuments && !documentSearch.searchQuery) {
      return null;
    }

    return (
      <div className="flex items-center justify-start mt-4 mb-2">
        <div className="ml-16 mr-4">
          {documentSearch.hasRelevantDocuments ? (
            <div className="flex items-center space-x-2">
              <Tag color="green">📄 找到相关文档</Tag>
              {documentSearch.documentSources.length > 0 && (
                <span className="text-sm text-gray-600">
                  来源：{documentSearch.documentSources.join(", ")}
                </span>
              )}
              {documentSearch.similarityScore && (
                <span className="text-sm text-blue-600">
                  相似度：{(documentSearch.similarityScore * 100).toFixed(1)}%
                </span>
              )}
            </div>
          ) : (
            <div className="flex items-center space-x-2">
              <Tag color="orange">🔍 未找到相关文档</Tag>
              <span className="text-sm text-gray-600">
                将使用大模型知识回答
              </span>
            </div>
          )}
        </div>
      </div>
    );
  };

  return (
    <>
      {contextHolder}
      {/* 自动TTS控制面板 */}
      <div className="flex items-center justify-between mb-4 px-4 py-2 bg-gray-50 rounded-lg">
        <div className="flex items-center space-x-2">
          <span className="text-sm font-medium text-gray-700">自动语音播放：</span>
          <Checkbox
            checked={autoTTSEnabled}
            onChange={(e) => setAutoTTSEnabled(e.target.checked)}
          >
            <span className="text-sm text-gray-600">AI回答完成后自动播放语音</span>
          </Checkbox>
        </div>
        {autoTTSEnabled && (
          <div className="flex items-center space-x-2">
            <Tag color="blue">🎵 自动播放已开启</Tag>
          </div>
        )}
      </div>
      <div className="flex flex-col h-full overflow-y-auto home-content-bg" ref={chatListRef}>
        {/* 选择模式控制栏 */}
        {messages.length > 1 && (
          <div className="flex items-center justify-between p-4 bg-gray-50 border-b">
            <div className="flex items-center gap-4">
              <Button
                type={isSelectionMode ? "primary" : "default"}
                onClick={() => setIsSelectionMode(!isSelectionMode)}
                icon={isSelectionMode ? <CheckSquareOutlined /> : <BorderOutlined />}
              >
                {isSelectionMode ? '退出选择' : '选择模式'}
              </Button>
              
              {isSelectionMode && (
                <>
                  <Button size="small" onClick={handleSelectAll}>
                    全选
                  </Button>
                  <Button size="small" onClick={handleDeselectAll}>
                    取消全选
                  </Button>
                  <Button 
                    type="primary" 
                    size="small" 
                    onClick={handleConvertSelected}
                    disabled={selectedMessages.length === 0}
                    icon={<AudioOutlined />}
                  >
                    转换选中 ({selectedMessages.length})
                  </Button>
                </>
              )}
            </div>
            
            {isSelectionMode && selectedMessages.length > 0 && (
              <span className="text-sm text-gray-600">
                已选择 {selectedMessages.length} 条消息
              </span>
            )}
          </div>
        )}

        {messages.map((item, index) => {
          return (
            <Fragment key={index}>
              {item.role === "user" ? (
                // user
                <div className={`flex items-center justify-end ${index !== 0 && "mt-8"}`}>
                  <div className="flex items-center gap-2">
                    {isSelectionMode && (
                      <Checkbox
                        checked={isMessageSelected(index)}
                        onChange={() => handleMessageSelect(index, item.content, 'user')}
                        className="mr-2"
                      />
                    )}
                    <div 
                      className="user-bubble p-4 rounded-8 m-4 relative group cursor-pointer"
                      onMouseEnter={() => {
                        // 悬停时自动触发TTS生成
                        if (!ttsStates[index.toString()] || ttsStates[index.toString()].status === 'idle') {
                          handleSingleMessageTTS(index.toString(), item.content, 'user');
                        }
                      }}
                      onClick={() => {
                        // 点击时如果已完成则下载，如果失败则重试
                        if (ttsStates[index.toString()]?.status === 'completed') {
                          handleSingleMessageTTS(index.toString(), item.content, 'user');
                        } else if (ttsStates[index.toString()]?.status === 'error') {
                          handleSingleMessageTTS(index.toString(), item.content, 'user');
                        }
                      }}
                    >
                      {item.content}
                      <Tooltip title={getTTSTooltip(index.toString())} placement="top">
                        <div className="absolute top-2 right-2 opacity-0 group-hover:opacity-100 transition-opacity tts-icon">
                          {getTTSIcon(index.toString())}
                        </div>
                      </Tooltip>
                    </div>
                  </div>
                  <Avatar style={{ verticalAlign: "middle", background: '#60a5fa', color: '#fff' }} size="large" className="min-w-40">
                    user
                  </Avatar>
                </div>
              ) : (
                // assistant
                <div className={`flex items-center justify-start ${index !== 0 && "mt-8"}`}>
                  <Avatar style={{ verticalAlign: "middle", background: '#818cf8' }} size="large" src={AvatarImage}>
                    鼎盛
                  </Avatar>
                  <div className="flex-1 p-4 m-4 assistant-bubble">
                    {/* 思考 */}
                    {item.reasoningContent && (
                      <>
                        <div className="flex items-center justify-between mb-2">
                          <span className="reasoning-tag">
                            {item.reasoningTime ? `思考中（用时${item.reasoningTime}秒）` : "已深度思考"}
                          </span>
                          {isSelectionMode && (
                            <Checkbox
                              checked={isMessageSelected(index)}
                              onChange={() => handleMessageSelect(index, item.reasoningContent || '', 'assistant')}
                              className="mr-2"
                            />
                          )}
                        </div>
                        <div 
                          className="reasoning-bubble mt-8 relative group cursor-pointer"
                          onMouseEnter={() => {
                            // 悬停时自动触发TTS生成（为思考内容创建唯一的索引）
                            const reasoningIndex = `reasoning_${index}`;
                            if (!ttsStates[reasoningIndex] || ttsStates[reasoningIndex].status === 'idle') {
                              handleSingleMessageTTS(reasoningIndex, item.reasoningContent || '', 'assistant');
                            }
                          }}
                          onClick={() => {
                            // 点击时如果已完成则下载，如果失败则重试
                            const reasoningIndex = `reasoning_${index}`;
                            if (ttsStates[reasoningIndex]?.status === 'completed') {
                              handleSingleMessageTTS(reasoningIndex, item.reasoningContent || '', 'assistant');
                            } else if (ttsStates[reasoningIndex]?.status === 'error') {
                              handleSingleMessageTTS(reasoningIndex, item.reasoningContent || '', 'assistant');
                            }
                          }}
                        >
                          <MarkdownRenderer markdown={item.reasoningContent} />
                          <Tooltip title={getTTSTooltip(`reasoning_${index}`)} placement="top">
                            <div className="absolute top-2 right-2 opacity-0 group-hover:opacity-100 transition-opacity tts-icon">
                              {getTTSIcon(`reasoning_${index}`)}
                            </div>
                          </Tooltip>
                        </div>
                      </>
                    )}
                    <div className="flex items-center justify-between">
                      <div 
                        className="flex-1 relative group"
                        onMouseEnter={() => {
                          hoverToPlayRef.current[index.toString()] = true;
                          if (!ttsStates[index.toString()] || ttsStates[index.toString()].status === 'idle') {
                            handleSingleMessageTTS(index.toString(), item.content, 'assistant');
                          } else if (ttsStates[index.toString()]?.status === 'completed') {
                            const a = audioRefs.current[index.toString()];
                            if (a) {
                              // 停止其他
                              Object.keys(audioRefs.current).forEach(k => {
                                if (k !== index.toString()) audioRefs.current[k]?.pause();
                              });
                              a.currentTime = 0;
                              a.play().catch(() => {});
                              currentlyPlayingKeyRef.current = index.toString();
                            }
                          }
                        }}
                        onMouseLeave={() => {
                          hoverToPlayRef.current[index.toString()] = false;
                          const a = audioRefs.current[index.toString()];
                          if (a) a.pause();
                          if (currentlyPlayingKeyRef.current === index.toString()) {
                            currentlyPlayingKeyRef.current = null;
                          }
                        }}
                      >
                        {ttsStates[index.toString()]?.audioUrl && (
                          <audio
                            ref={(el) => { audioRefs.current[index.toString()] = el; }}
                            preload="none"
                            src={ttsStates[index.toString()]!.audioUrl}
                            style={{ display: 'none' }}
                          />
                        )}
                        <MarkdownRenderer markdown={item.content} />
                        <Tooltip title={getTTSTooltip(index.toString())} placement="top">
                          <div className="absolute top-2 right-2 opacity-0 group-hover:opacity-100 transition-opacity tts-icon">
                            {getTTSIcon(index.toString())}
                          </div>
                        </Tooltip>
                      </div>
                      <div className="flex items-center gap-2">
                        {isSelectionMode && !item.reasoningContent && (
                          <Checkbox
                            checked={isMessageSelected(index)}
                            onChange={() => handleMessageSelect(index, item.content, 'assistant')}
                          />
                        )}
                      </div>
                    </div>
                  </div>
                </div>
              )}
            </Fragment>
          );
        })}
        {/* 思考中 */}
        {isLoading && (
          <div className="flex items-center justify-start mt-8">
            <Avatar style={{ verticalAlign: "middle", background: '#818cf8' }} size="large" src={AvatarImage}>
              鼎盛
            </Avatar>
            <div className="flex-1 p-4 m-4 assistant-bubble">
              <div className="flex items-center gap-2">
                <Spin size="small" />
                <span>正在思考中...</span>
              </div>
              {currentReasoning && (
                <div className="reasoning-bubble mt-8">
                  <MarkdownRenderer markdown={currentReasoning} />
                </div>
              )}
              {currentAnswer && (
                <div className="mt-8">
                  <MarkdownRenderer markdown={currentAnswer} />
                </div>
              )}
            </div>
          </div>
        )}
        {renderDocumentSearchStatus()}
      </div>
    </>
  );
};

// 全局样式插入
if (typeof document !== 'undefined') {
  const style = document.createElement('style');
  style.innerHTML = `
    .home-content-bg {
      background: transparent;
    }
    .user-bubble {
      background: linear-gradient(90deg, #dbeafe 0%, #f0fdfa 100%);
      color: #2563eb;
      font-weight: 500;
      box-shadow: 0 2px 8px rgba(80, 112, 255, 0.06);
    }
    .assistant-bubble {
      background: linear-gradient(90deg, #f3f4f6 0%, #ede9fe 100%);
      color: #3730a3;
      font-weight: 500;
      border-radius: 12px;
      box-shadow: 0 2px 8px rgba(129, 140, 248, 0.06);
    }
    .reasoning-tag {
      display: inline-block;
      background: #f0f9ff;
      color: #0ea5e9;
      border-radius: 6px;
      padding: 2px 12px;
      font-size: 13px;
      margin-bottom: 6px;
    }
    .reasoning-bubble {
      background: #f1f5f9;
      color: #64748b;
      border-radius: 8px;
      padding: 10px 14px;
      font-size: 14px;
    }
    
    /* TTS相关样式 */
    .user-bubble:hover,
    .assistant-bubble:hover,
    .reasoning-bubble:hover {
      transform: translateY(-1px);
      box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
      transition: all 0.2s ease-in-out;
    }
    
    .tts-icon {
      transition: all 0.2s ease-in-out;
      cursor: pointer;
    }
    
    .tts-icon:hover {
      transform: scale(1.1);
    }
    
    .tts-loading {
      animation: spin 1s linear infinite;
    }
    
    @keyframes spin {
      from { transform: rotate(0deg); }
      to { transform: rotate(360deg); }
    }
  `;
  document.head.appendChild(style);
}

export default Content;
